// 通过管道流，读一点，写一点

// const ReadStream = require('./ReadStream');
// const WriteStream = require('./WriteStream');
// const path = require('path');

// let rs = new ReadStream(path.resolve(__dirname, '1.txt'), {
//   highWaterMark: 4,
// });

// let ws = new WriteStream(path.resolve(__dirname, 'copy.txt'), {
//   highWaterMark: 1,
// });

// rs.pipe(ws); // 拷贝功能是异步，内部用的是发布订阅

/* rs.on('data', function (chunk) {
  console.log(chunk);
  let flag = ws.write(chunk);
  if (!flag) {
    rs.pause();
  }
});
ws.on('drain', function () {
  rs.resume();
}); */

/* function pipe(ws) {
  this.on('data',  (chunk) => {
    let flag = ws.write(chunk);
    if (!flag) {
      this.pause();
    }
  })
  ws.on('drain',  () => {
    this.resume();
  });

} */
const { Transform, Duplex } = require('stream');
// 可读流，可写流，双工流（能读也能写，既继承了可读又继承了可写流，读和写没有关系）

class MyDuplex extends Duplex {
  _read() {
    this.push('xxx');
    this.push(null);
  }
  _write(chunk, encoding, cb) {
    console.log(chunk);
    cb();
  }
}

let md = new MyDuplex();
md.on('data', function (chunk) {
  console.log(chunk);
});
md.write('ok');

// 转化流：加密，压缩，可以把可写流转化成可读流

class MyTransform extends Transform {
  _transform(chunk, encoding, cb) {
    // console.log(chunk);
    this.push(chunk.toString().toUpperCase());
    // 清空缓存，将writable置为false，才可以继续写入
    cb();
  }
}

let my = new MyTransform();

// 监视用户输入，触发回调
/* process.stdin.on('data', function (chunk) {
  console.log(chunk);
  // 把用户输入原样输入
  process.stdout.write(chunk);
}); */

// process.stdout.write('ok'); // 标准输出，跟console.log一样，可写流
// process.stdin.pipe(process.stdout);

process.stdin.pipe(my).pipe(process.stdout);
